package shop.ynubeggar.service.impl;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import shop.ynubeggar.constant.RedisCacheKey;
import shop.ynubeggar.interceptor.LoginInterceptor;
import shop.ynubeggar.model.valueobject.CartItemVO;
import shop.ynubeggar.model.valueobject.LoginUser;
import shop.ynubeggar.service.CartService;

import javax.annotation.Resource;
import java.util.Map;

@Slf4j
@Service
public class CartServiceImpl implements CartService {

    @Resource
    RedisTemplate redisTemplate;


    /**
     * 更改购物车单项，类似添加商品到购物车，只是讲数目设置为请求的数目
     *
     * @param
     */
    @Override
    public void updateCart(Map<Long, Integer> map) {
//        FIXME 这里取不到购物车，不知道为啥
        BoundHashOperations<String, Long, String> myCart = getCart();
        for (Long key : map.keySet()) {
            long productId = key;

            int buyNum = map.get(key);

//            商品存在
            CartItemVO cartItemVO = JSONUtil.toBean(myCart.get(productId), CartItemVO.class);
            cartItemVO.setBuyNum(cartItemVO.getBuyNum() - buyNum);
            myCart.put(productId, JSONUtil.toJsonStr(cartItemVO));
        }
    }


    /**
     * 获取当前用户的购物车
     *
     * @return
     */
    public BoundHashOperations<String, Long, String> getCart() {
        String key = produceCartKey();
        return redisTemplate.boundHashOps(key);
    }

    /**
     * 产生购物车key
     *
     * @return
     */
    private String produceCartKey() {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        return String.format(RedisCacheKey.CHART_KEY, loginUser.getId());
    }
}
